package com.mab.apipassenger.service;


import com.alibaba.cloud.commons.lang.StringUtils;
import com.mab.apipassenger.remote.ServicePassengerUserClient;
import com.mab.apipassenger.remote.ServiceVeificationcodeClient;
import com.msb.internalcommon.constant.CommonStatusEnum;
import com.msb.internalcommon.constant.IdentityConstant;
import com.msb.internalcommon.constant.TokenConstants;
import com.msb.internalcommon.dto.ResponseResult;
import com.msb.internalcommon.reponese.NumberCodeResponse;
import com.msb.internalcommon.reponese.TokenResponse;
import com.msb.internalcommon.request.VerificationCodeDTO;
import com.msb.internalcommon.util.JwtUtils;
import com.msb.internalcommon.util.RedisPrefixUtils;
import io.netty.util.internal.StringUtil;
import com.mab.apipassenger.remote.ServiceVeificationcodeClient;
import com.msb.internalcommon.dto.ResponseResult;
import com.msb.internalcommon.reponese.NumberCodeResponse;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Auther: jiudianliu
 * @Date: 2023/3/17 - 03 - 17 - 15:18
 * @Description: com.mab.apipassenger.service
 * @version: 1.0
 */
@Service
public class VerificationCodeService {

    @Autowired
    private ServiceVeificationcodeClient serviceVeificationcodeClient ;

    //注入service-passenger-user相关服务的接口
    @Autowired
    private ServicePassengerUserClient servicePassengerUserClient ;

    @Autowired
    private StringRedisTemplate stringRedisTemplate ;


    /**
     * 生成验证码
     * @param passengerPhone 手机号
     * @return
     */

    public ResponseResult generatorCode(String passengerPhone){
        //调用验证码服务，获取验证码
        ResponseResult<NumberCodeResponse> numberCodeResponse = serviceVeificationcodeClient.getNumberCode(6);
        int numberCode = numberCodeResponse.getData().getNumberCode();
        //System.out.println("验证码：" + numberCode);

        //存入redis
        //key,value,过期时间
        String key = RedisPrefixUtils.generatorKeyByPhone(passengerPhone , IdentityConstant.PASSENGER_IDENTITY) ;
        stringRedisTemplate.opsForValue().set( key , numberCode + "", 2 , TimeUnit.MINUTES);
        return ResponseResult.success(" ");
    }

    /**
     * 校验验证码
     * @param passengerPhone  手机号
     * @param verificationCode  验证码
     * @return
     */
    public ResponseResult checkCode (String passengerPhone , String verificationCode){

        // 根据手机号，去redis读取验证码
        // 生成key
        String key = RedisPrefixUtils.generatorKeyByPhone(passengerPhone , IdentityConstant.PASSENGER_IDENTITY);

        // 根据key获取value
        String codeRedis = stringRedisTemplate.opsForValue().get(key);
        System.out.println("Redis中的value：" + codeRedis);

        //校验验证码
        if (StringUtils.isBlank(codeRedis))
            return ResponseResult.fail(CommonStatusEnum.VERIFICATION_CODE_ERROR.getCode(), CommonStatusEnum.VERIFICATION_CODE_ERROR.getValue());
        if (!verificationCode.trim().equals(codeRedis.trim())){
            return ResponseResult.fail(CommonStatusEnum.VERIFICATION_CODE_ERROR.getCode(),CommonStatusEnum.VERIFICATION_CODE_ERROR.getValue());
        }

        // 判断原来是否有用户，并进行对应的处理
        VerificationCodeDTO verificationCodeDTO = new VerificationCodeDTO() ;
        verificationCodeDTO.setPassengerPhone(passengerPhone) ;
        servicePassengerUserClient.loginOrRegister(verificationCodeDTO) ;

        // 颁发令牌 , 身份验证用常量值或枚举
        String accessToken = JwtUtils.generatorToken(passengerPhone, IdentityConstant.PASSENGER_IDENTITY, TokenConstants.ACCESS_TOKEN_TYPE);
        String refreshToken = JwtUtils.generatorToken(passengerPhone, IdentityConstant.PASSENGER_IDENTITY,TokenConstants.REFRESH_TOKEN_TYPE);

        // 将Token存入Redis
        //accessToken 设置过期时间为30天
        //refreshToken  设置过期时间为31天  比access多一天
        String accessTokenKey = RedisPrefixUtils.generatorTokenKey(passengerPhone, IdentityConstant.PASSENGER_IDENTITY , TokenConstants.ACCESS_TOKEN_TYPE);
        stringRedisTemplate.opsForValue().set(accessTokenKey , accessToken , 30 , TimeUnit.DAYS);
        String refreshTokenKey = RedisPrefixUtils.generatorTokenKey(passengerPhone, IdentityConstant.PASSENGER_IDENTITY , TokenConstants.REFRESH_TOKEN_TYPE);
        stringRedisTemplate.opsForValue().set(refreshTokenKey , refreshToken , 31 , TimeUnit.DAYS);

        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(accessToken);
        tokenResponse.setRefreshToken(refreshToken);
        return ResponseResult.success(tokenResponse);
    }
}
